package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.dto.GeConSocialCritiqueDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.CritiqueQuery;
import com.htgd.gardenexpo.page.SocialContentQuery;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.HttpRequest;
import com.htgd.gardenexpo.utils.IpUtils;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.utils.WeChatUtils;
import com.htgd.gardenexpo.vo.GeConCritiqueVO;
import com.htgd.gardenexpo.vo.GeConSocialContentVO;
import com.htgd.gardenexpo.vo.MyTaskDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 社交内容 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-08
 */
@Slf4j
@Service
public class GeConSocialContentServiceImpl extends ServiceImpl<GeConSocialContentMapper, GeConSocialContent> implements IGeConSocialContentService {

    @Autowired
    private GeConSocialContentMapper geConSocialContentMapper;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private GeConLonLatMapper geConLonLatMapper;

    @Autowired
    private GeConSocialLikesMapper geConSocialLikesMapper;

    @Autowired
    private GeConSocialCritiqueMapper geConSocialCritiqueMapper;

    @Autowired
    private WeChatUtils weChatUtils;

    @Autowired
    private GeConSocialContentReviewMapper geConSocialContentReviewMapper;

    @Autowired
    private IGeConFreeSportsService geConFreeSportsService;

    @Autowired
    private IGeConGoalSportsService geConGoalSportsService;

    @Autowired
    private IGeConChallengeSportsService geConChallengeSportsService;

    @Autowired
    private IGeConDailyDataDeckService geConDailyDataDeckService;

    @Autowired
    private IGeConLeisureDataDeckService geConLeisureDataDeckService;

    @Transactional
    @Override
    public CommonResult add(GeConSocialContent geConSocialContent, String openId) {
        //资源不能为null
        if ("1".equals(geConSocialContent.getType()) && geConSocialContent.getImgPath()==null){
            return CommonResult.error("请上传图片资源,不可为空");
        }
        if ("2".equals(geConSocialContent.getType()) && geConSocialContent.getVideoPath()==null){
            return CommonResult.error("请上传视频资源,不可为空");
        }

        geConSocialContent.setOpenId(openId);

        //内容审核
        JSONObject responseJSON = weChatUtils.msgCheck(geConSocialContent.getContent(), openId);
        Integer errcode = responseJSON.getInteger("errcode");
        if(errcode==0){
            JSONObject result = responseJSON.getJSONObject("result");
            String suggest = result.getString("suggest");
            if("pass".equals(suggest)){
                geConSocialContent.setStatus("1");
            }else {
                log.info("内容检查不通过，原因："+responseJSON);
                return CommonResult.error("所发内容涉及违规");
            }
        }else {
            return CommonResult.error("内容审核失败，请稍后再试");
        }

        geConSocialContent.setIpAddress(IpUtils.getRealAddressByIP(geConSocialContent.getIp()));
        geConSocialContent.setStatus("0");
        geConSocialContentMapper.insert(geConSocialContent);

        if("1".equals(geConSocialContent.getType())){//海报
            //图片审核
            String[] images = geConSocialContent.getImgPath().split(",");
            for (String image : images) {
                JSONObject jsonObject = weChatUtils.mediaCheck(image, openId);
                Integer errcode1 = jsonObject.getInteger("errcode");

                if(errcode1==0){
                    //插入审核记录
                    String trace_id = jsonObject.getString("trace_id");
                    GeConSocialContentReview geConSocialContentReview = new GeConSocialContentReview();
                    geConSocialContentReview.setTraceId(trace_id);
                    geConSocialContentReview.setImgPath(image);
                    geConSocialContentReview.setStatus("0");
                    geConSocialContentReview.setContentId(geConSocialContent.getId());
                    geConSocialContentReviewMapper.insert(geConSocialContentReview);

                }else {
                    return CommonResult.error("图片审核失败，请稍后再试");
                }
            }
        }

        return CommonResult.success("添加成功");
    }

    @Override
    public PageInfo<GeConSocialContentVO> pageList(SocialContentQuery socialContentQuery, String openId) {
        PageHelper.startPage(socialContentQuery.getPageNum(), socialContentQuery.getPageSize());
        List<GeConSocialContentVO> list = geConSocialContentMapper.pageList(socialContentQuery);
        for (GeConSocialContentVO geConSocialContentVO : list) {
            //类型
            if("1".equals(geConSocialContentVO.getType())){
                geConSocialContentVO.setTypeText("海报");
            }else{
                geConSocialContentVO.setTypeText("Vlog");
            }

            if(geConSocialContentVO.getStatus()!=null){//状态
                geConSocialContentVO.setStatusText(geBaseDictService.getTextByCodeAndValue("bpm",geConSocialContentVO.getStatus()));
            }
            if(openId!=null&&openId!=""){
                GeConSocialLikes conSocialContentLikes = geConSocialLikesMapper.selectOne(new LambdaQueryWrapper<GeConSocialLikes>()
                        .eq(GeConSocialLikes::getContentId,geConSocialContentVO.getId())
                        .eq(GeConSocialLikes::getOpenId,openId));
                if(Objects.nonNull(conSocialContentLikes)){
                    geConSocialContentVO.setLikes(true);
                }else{
                    geConSocialContentVO.setLikes(false);
                }
            }

            //评论数
            Long discussNumber = geConSocialCritiqueMapper.selectCount(new LambdaQueryWrapper<GeConSocialCritique>()
                    .eq(GeConSocialCritique::getContentId,geConSocialContentVO.getId())
                    .eq(GeConSocialCritique::getType,"1")
                    .eq(GeConSocialCritique::getStatus,"1"));
            geConSocialContentVO.setReviewNumber(Math.toIntExact(discussNumber));

            //运动数据
            if(geConSocialContentVO.getSportsId()!=null && geConSocialContentVO.getSportsType() !=null){
                if("1".equals(geConSocialContentVO.getSportsType())){//自由跑
                    CommonResult taskDetails = geConFreeSportsService.getTaskDetails(geConSocialContentVO.getSportsId());
                    if(taskDetails!=null && 200==taskDetails.getCode()){
                        geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                    }
                }
                if("2".equals(geConSocialContentVO.getSportsType())){//目标跑
                    CommonResult taskDetails = geConGoalSportsService.getTaskDetails(geConSocialContentVO.getSportsId());
                    if(taskDetails!=null && 200==taskDetails.getCode()){
                        geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                    }
                }
                if("3".equals(geConSocialContentVO.getSportsType())){//挑战跑
                    CommonResult taskDetails = geConChallengeSportsService.getTaskDetails(geConSocialContentVO.getSportsId());
                    if(taskDetails!=null && 200==taskDetails.getCode()){
                        geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                    }
                }
                if("4".equals(geConSocialContentVO.getSportsType())){//智慧起跑线
                    CommonResult taskDetails = geConDailyDataDeckService.getTaskDetails(geConSocialContentVO.getSportsId());
                    if(taskDetails!=null && 200==taskDetails.getCode()){
                        geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                    }
                }
                if("5".equals(geConSocialContentVO.getSportsType())){//挑战
                    CommonResult taskDetails = geConLeisureDataDeckService.getTaskDetails(geConSocialContentVO.getSportsId());
                    if(taskDetails!=null && 200==taskDetails.getCode()){
                        geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                    }
                }
            }
        }
        return new PageInfo<>(list);

    }

    /**
     * 查看详情
     * @param contentId 社交内容ID
     * @param openId 微信小程序用户唯一标识
     * @return
     */
    @Override
    public GeConSocialContentVO getGeConSocialContentById(String contentId, String openId) {
        GeConSocialContentVO geConSocialContentVO = geConSocialContentMapper.getGeConSocialContentById(contentId);
        if(openId!=null&&openId!=""){
            GeConSocialLikes conSocialContentLikes = geConSocialLikesMapper.selectOne(new LambdaQueryWrapper<GeConSocialLikes>()
                    .eq(GeConSocialLikes::getContentId,geConSocialContentVO.getId())
                    .eq(GeConSocialLikes::getOpenId,openId));
            if(Objects.nonNull(conSocialContentLikes)){
                geConSocialContentVO.setLikes(true);
            }else{
                geConSocialContentVO.setLikes(false);
            }
        }
        Long discussNumber = geConSocialContentMapper.selectCount(new LambdaQueryWrapper<GeConSocialContent>()
            .eq(GeConSocialContent::getTopicId,geConSocialContentVO.getTopicId())
            .eq(GeConSocialContent::getStatus,"1"));
        geConSocialContentVO.setDiscussNumber(discussNumber.intValue());

        //运动数据
        if(geConSocialContentVO.getSportsId()!=null && geConSocialContentVO.getSportsType() !=null){
            if("1".equals(geConSocialContentVO.getSportsType())){//自由跑
                CommonResult taskDetails = geConFreeSportsService.getTaskDetails(geConSocialContentVO.getSportsId());
                if(taskDetails!=null && 200==taskDetails.getCode()){
                    geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                }
            }
            if("2".equals(geConSocialContentVO.getSportsType())){//目标跑
                CommonResult taskDetails = geConGoalSportsService.getTaskDetails(geConSocialContentVO.getSportsId());
                if(taskDetails!=null && 200==taskDetails.getCode()){
                    geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                }
            }
            if("3".equals(geConSocialContentVO.getSportsType())){//挑战跑
                CommonResult taskDetails = geConChallengeSportsService.getTaskDetails(geConSocialContentVO.getSportsId());
                if(taskDetails!=null && 200==taskDetails.getCode()){
                    geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                }
            }
            if("4".equals(geConSocialContentVO.getSportsType())){//智慧起跑线
                CommonResult taskDetails = geConDailyDataDeckService.getTaskDetails(geConSocialContentVO.getSportsId());
                if(taskDetails!=null && 200==taskDetails.getCode()){
                    geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                }
            }
            if("5".equals(geConSocialContentVO.getSportsType())){//挑战
                CommonResult taskDetails = geConLeisureDataDeckService.getTaskDetails(geConSocialContentVO.getSportsId());
                if(taskDetails!=null && 200==taskDetails.getCode()){
                    geConSocialContentVO.setMyTaskDetails((MyTaskDetails) taskDetails.getData());
                }
            }
        }
        return geConSocialContentVO;
    }

    /**
     * 根据经纬度查询市区
     * @param lon 经度
     * @param lat 纬度
     * @return
     */
    @Override
    public List<GeConLonLat> selectGeConLonLat(String lon,String lat) {
        List<GeConLonLat> geConLonLatList = geConLonLatMapper.selectList(new LambdaQueryWrapper<GeConLonLat>()
        .eq(GeConLonLat::getLon,lon).eq(GeConLonLat::getLat,lat));
        return geConLonLatList;
    }

    /**
     * 通过第三方接口查询市区
     * @param lon 经度
     * @param lat 纬度
     * @param ip
     * @return
     */
    @Override
    public Map<String, Object> getAreaCode(String lon, String lat,String ip) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        // 拼接请求的url
        String url = "http://whois.pconline.com.cn/ipAreaCoordJson.jsp?json=true&coords="+new BigDecimal(lon).doubleValue()+","+new BigDecimal(lat).doubleValue()+"&ip="+ip;
        // HttpUtil为封装的http请求工具类
        String result = HttpRequest.sendGetRequest(url);
        log.info("result:===>【{}】",result);
        //Java语言从json格式中提取数据
        JSONObject resultJson = JSONObject.parseObject(result);
        //省份
        String pro = resultJson.getString("pro");
        String proCode = resultJson.getString("proCode");
        //城市
        String city = resultJson.getString("city");
        String cityCode = resultJson.getString("cityCode");
        String district = resultJson.getString("region");
        String districtCode = resultJson.getString("regionCode");
        map.put("pro",pro);
        map.put("city",city);
        map.put("district",district);
        log.info("map:===>【{}】",map);
        GeConLonLat geConLonLat = new GeConLonLat();
        geConLonLat.setPCode(proCode);
        geConLonLat.setPro(pro);
        geConLonLat.setCCode(cityCode);
        geConLonLat.setCity(city);
        geConLonLat.setDCode(districtCode);
        geConLonLat.setDistrict(district);
        geConLonLat.setLon(lon);
        geConLonLat.setLat(lat);
        geConLonLatMapper.insert(geConLonLat);
        return map;
    }

    /**
     * 点赞及取消点赞
     * @param contentId 社交内容ID
     * @param openId 微信小程序用户唯一标识
     * @return
     */
    @Transactional
    @Override
    public synchronized CommonResult likes(String contentId, String openId) {
        GeConSocialLikes conSocialContentLikes = geConSocialLikesMapper.selectOne(new LambdaQueryWrapper<GeConSocialLikes>()
            .eq(GeConSocialLikes::getContentId,contentId)
            .eq(GeConSocialLikes::getOpenId,openId));
        if(Objects.isNull(conSocialContentLikes)){
            GeConSocialLikes geConSocialContentLikes = new GeConSocialLikes();
            geConSocialContentLikes.setOpenId(openId);
            geConSocialContentLikes.setContentId(contentId);
            geConSocialContentLikes.setLikeTime(LocalDateTime.now());
            geConSocialLikesMapper.insert(geConSocialContentLikes);
            GeConSocialContent geConSocialContent = geConSocialContentMapper.selectById(contentId);
            geConSocialContent.setLikeNumber(geConSocialContent.getLikeNumber()+1);
            geConSocialContentMapper.updateById(geConSocialContent);
            return CommonResult.success("点赞成功");
        }
        geConSocialLikesMapper.delete(new LambdaQueryWrapper<GeConSocialLikes>()
                .eq(GeConSocialLikes::getContentId,contentId)
                .eq(GeConSocialLikes::getOpenId,openId));
        GeConSocialContent geConSocialContent = geConSocialContentMapper.selectById(contentId);
        geConSocialContent.setLikeNumber(geConSocialContent.getLikeNumber()-1);
        geConSocialContentMapper.updateById(geConSocialContent);
        return CommonResult.success("取消成功");
    }

    /**
     * 评论及回复
     * @param geConSocialCritique
     * @param request
     * @return
     */
    @Transactional
    @Override
    public synchronized CommonResult commentReply(GeConSocialCritiqueDTO geConSocialCritique, HttpServletRequest request) {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        GeConSocialCritique geConSocialCritique1 = new GeConSocialCritique();

        //内容检查
        JSONObject responseJSON = weChatUtils.msgCheck(geConSocialCritique.getContent(), openId);
        Integer errcode = responseJSON.getInteger("errcode");
        if(errcode==0){
            JSONObject result = responseJSON.getJSONObject("result");
            String suggest = result.getString("suggest");
            if("pass".equals(suggest)){
                geConSocialCritique1.setStatus("1");
            }else {
                log.info("内容检查不通过，原因："+responseJSON);
                return CommonResult.error("所发内容涉及违规");
            }
        }else {
            return CommonResult.error("内容审核失败，请稍后再试");
        }

        geConSocialCritique1.setOpenId(openId);
        geConSocialCritique1.setContentId(geConSocialCritique.getContentId());
        geConSocialCritique1.setContent(geConSocialCritique.getContent());
        geConSocialCritique1.setType(geConSocialCritique.getType());
        geConSocialCritique1.setCreateTime(LocalDateTime.now());
        geConSocialCritique1.setIp(IpUtils.getUserIP(request));
        geConSocialCritique1.setIpAddress(IpUtils.getRealAddressByIP(geConSocialCritique1.getIp()));
        if(Objects.equals(geConSocialCritique.getType(),"1")){//评论
            geConSocialCritiqueMapper.insert(geConSocialCritique1);
            return CommonResult.success("评论成功");
        }

        //回复
        geConSocialCritique1.setReplyId(geConSocialCritique.getReplyId());
        geConSocialCritiqueMapper.insert(geConSocialCritique1);
        //评论回复数量加1
        geConSocialCritiqueMapper.updateNumById(geConSocialCritique.getReplyId());
        return CommonResult.success("回复成功");
    }

    /**
     * 查询评论列表
     * @param critiqueQuery
     * @return
     */
    @Override
    public PageInfo<GeConCritiqueVO> getPageCritiqueList(CritiqueQuery critiqueQuery,String openId) {
        PageHelper.startPage(critiqueQuery.getPageNum(), critiqueQuery.getPageSize());
        critiqueQuery.setOpenId(openId);
        List<GeConCritiqueVO> list = geConSocialCritiqueMapper.pageList(critiqueQuery);
        if(!list.isEmpty()){
            list.stream().forEach(item->{
                item.setGeConCritiques(geConSocialCritiqueMapper.getCritiqueReplyList(item.getId(),openId));
            });
        }
        return new PageInfo<>(list);
    }

    /**
     * 查询评论回复列表
     * @param critiqueQuery
     * @return
     */
    @Override
    public PageInfo<GeConCritiqueVO> getPageCritiqueReplyList(CritiqueQuery critiqueQuery,String openId) {
        PageHelper.startPage(critiqueQuery.getPageNum(), critiqueQuery.getPageSize());
        critiqueQuery.setOpenId(openId);
        List<GeConCritiqueVO> list = geConSocialCritiqueMapper.pageList(critiqueQuery);
        return new PageInfo<>(list);
    }

}
